__author__ = 'Thomas Kuczek'

import logging
import os
import time
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from datetime import datetime,timedelta

# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True

import datamodel
import userdetails
import searchfors

logging.getLogger().setLevel(logging.DEBUG)

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the current user in the 'user' variable and the current webapp request
  in the 'request' variable.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'login_url': users.create_login_url(self.request.uri),
      'logout_url': users.create_logout_url(self.request.uri),
      'debug': self.request.get('deb'),
      'application_name': 'Treffen wir uns heute?',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))

class MainHandler(BaseRequestHandler):
  def get(self):

    template_data = {}

    user = users.get_current_user()
    logging.debug('User ist: %s', str(user))

    if user:
      userdetail = userdetails.getUserdetails(user)
      searchfor  = searchfors.getSearchfors(user)
      if not userdetail:
        self.redirect('/userdetail')
        return
    else:
      userdetail = datamodel.Userdetails()
      searchfor = datamodel.Searchfors()
    
    template_data = {
      'user': user,
      'userdetail': userdetail,                   
      'searchfor': searchfor,                   
    }

    self.response.headers['Content-Type'] = 'text/html'
    self.generate('treffenwiruns.html', template_data)



class UserdetailHandler(BaseRequestHandler):
  def get(self):
    template_data = {}

    user = users.get_current_user()
    if not user:      
      self.redirect(users.create_login_url(self.request.uri))
      return

    userdetail = userdetails.getUserdetails(user)
    template_data = {
      'user': user,
      'userdetail': userdetail,
    }

    self.response.headers['Content-Type'] = 'text/html'
    self.generate('userdetails.html', template_data)
    
  def post(self):
    
    user = users.get_current_user()
    if not user:      
      self.redirect(users.create_login_url(self.request.uri))
      return
    
    gender = self.request.get('gender')
    sexuality = self.request.get('sexuality')
    birthDay = int(self.request.get('birthDay'))
    birthMonth = int(self.request.get('birthMonth'))
    birthYear = int(self.request.get('birthYear'))
    birthdate = datetime(birthYear, birthMonth, birthDay)
    country = self.request.get('country')
    city = self.request.get('city')

    userdetail = userdetails.getUserdetails(user)
    
    if userdetail:
      userdetail.gender = gender
      userdetail.sexuality = sexuality
      userdetail.birthdate = birthdate
      userdetail.country = country
      userdetail.city = city
      userdetail.put()
      
    else:
      userdetail = userdetails.setUserdetails(user, gender, sexuality, birthdate, country, city)
      
    self.redirect('/userdetail')

class SearchforHandler(BaseRequestHandler):
  def get(self):
    template_data = {}
    
    user = users.get_current_user()
    if not user:      
      self.redirect(users.create_login_url(self.request.uri))
      return

    searchfor = searchfors.getSearchfors(user)
    if searchfor:
      template_data = {
        'user': user,
        'searchfor': searchfor,
      }
    else:
      template_data = {
        'user': user,
        'searchfor': searchfor,
      }

    self.response.headers['Content-Type'] = 'text/html'
    self.generate('searchfors.html', template_data)
    
  def post(self):
    
    user = users.get_current_user()
    if not user:      
      self.redirect(users.create_login_url(self.request.uri))
      return
    
    age_from = self.request.get('age_from')
    age_to = self.request.get('age_to')
    gender = self.request.get('gender')
    searchfor = searchfors.getSearchfors(user)
    
    if searchfor:
      searchfor.age_from = int(age_from)
      searchfor.age_to = int(age_to)
      searchfor.gender = str(gender)
      searchfor.put()
    else:
      searchfor = searchfors.setSearchfors(user, age_from, age_to, gender)
      
    self.redirect('/searchfor')

class MatchHandler(BaseRequestHandler):
  def get(self):
    template_data = {}

    user = users.get_current_user()

    if user:
      userdetail = userdetails.getUserdetails(user)
      searchfor  = searchfors.getSearchfors(user)
      if not userdetail:
        self.redirect('/userdetail')
        return
      if not searchfor:
        self.redirect('/searchfor')
        return
      
    else:
      userdetail = datamodel.Userdetails()
      searchfor = datamodel.Searchfors()

    query = db.Query(datamodel.Userdetails)
    if searchfor.gender != 'whatever':
      query.filter('gender =', searchfor.gender)
    if searchfor.age_from:
      query.filter('birthdate <', datetime.now() - timedelta(days=searchfor.age_from*365) )
    if searchfor.age_to:
      query.filter('birthdate >', datetime.now() - timedelta(days=searchfor.age_to*365) )
    if userdetail.country:
      query.filter('country =', userdetail.country)
    if userdetail.city:
      query.filter('city =', userdetail.city)

    logging.debug('Gql ist: %s', query)

    matches = query.fetch(100)
    
    template_data = {
      'user': user,
      'userdetail': userdetail,                   
      'searchfor': searchfor,                   
      'matches': matches,                   
    }

    self.response.headers['Content-Type'] = 'text/html'
    self.generate('matches.html', template_data)

class AdminUsersHandler(BaseRequestHandler):
  def get(self):
    template_data = {}

    user = users.get_current_user()

    if not users.is_current_user_admin():
      self.redirect('/')
      return

    logging.debug('Admin eingeloggt!')

    userdetail = userdetails.getUserdetails(user)

    query = db.Query(datamodel.Userdetails)
    logging.debug('Gql ist: %s', query)
    all_users = query.fetch(100)
    
    template_data = {
      'user': user,
      'userdetail': userdetail,                   
      'all_users': all_users,                   
    }

    self.response.headers['Content-Type'] = 'text/html'
    self.generate('admin/users.html', template_data)


if __name__ == '__main__':
  application = webapp.WSGIApplication(
      [
        ('/', MainHandler),
        ('/userdetail', UserdetailHandler),
        ('/searchfor', SearchforHandler),
        ('/match', MatchHandler),
        ('/admin/users', AdminUsersHandler),
      ],
      debug = True)

  wsgiref.handlers.CGIHandler().run(application)
